package com.szqhyxj.youxiangju.biz.merchantHome.my;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.szqhyxj.youxiangju.BasePromptFragment;
import com.szqhyxj.youxiangju.R;
import com.szqhyxj.youxiangju.biz.card.CardActivity;
import com.szqhyxj.youxiangju.biz.core.SharedPreferencesUtil;
import com.szqhyxj.youxiangju.biz.core.TokenManager;
import com.szqhyxj.youxiangju.biz.core.UserInfo;
import com.szqhyxj.youxiangju.biz.core.UserInfoManger;
import com.szqhyxj.youxiangju.biz.equipmentActivation.equipmentCardslot.EquipmentCardSlotActivity;
import com.szqhyxj.youxiangju.biz.equipmentActivation.headIdCard.HeadIdCardActivity;
import com.szqhyxj.youxiangju.biz.login.LoginActivity;
import com.szqhyxj.youxiangju.biz.merchantHome.shop.order.OrderListActivity;
import com.szqhyxj.youxiangju.biz.partnerHome.equipment.PartnerEquipmentActivity;
import com.szqhyxj.youxiangju.biz.personalInformation.PersonalInformationActivity;
import com.szqhyxj.youxiangju.biz.realNameAuth.idcard.IDCardAuthActivity;
import com.szqhyxj.youxiangju.biz.receivables.ReceivablesActivity;
import com.szqhyxj.youxiangju.biz.set.SettingActivity;
import com.szqhyxj.youxiangju.biz.web.WebActivity;
import com.szqhyxj.youxiangju.sys.components.HeadportraitView;
import com.szqhyxj.youxiangju.sys.components.view.popview.GoShopPopView;
import com.szqhyxj.youxiangju.sys.components.view.popview.RealNamePopView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by leung on 2018/10/30.
 */

public class MyFragment extends BasePromptFragment implements MyContract.View, IconAdapter.IconClickListener {

    @BindView(R.id.gocertification)
    TextView gocertification;

    @BindView(R.id.visible)
    LinearLayout visible;
    @BindView(R.id.none)
    LinearLayout none;

    @BindView(R.id.earnings)
    LinearLayout earnings;
    @BindView(R.id.cashwithdrawal)
    LinearLayout cashwithdrawal;
    @BindView(R.id.monthIncome)
    TextView monthIncome;
    @BindView(R.id.topArea)
    LinearLayout topArea;

    public static MyFragment newInstance() {
        Bundle args = new Bundle();
        MyFragment fragment = new MyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    Unbinder unbinder;
    @BindView(R.id.avatar)
    HeadportraitView avatar;
    @BindView(R.id.username)
    TextView username;

    @BindView(R.id.vipicon)
    ImageView vipicon;
    @BindView(R.id.partnericon)
    ImageView partnericon;
    @BindView(R.id.balance)
    TextView balance;
    @BindView(R.id.funcs)
    RecyclerView funcs;
    private MyContract.Presenter presenter;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (presenter == null) {
                presenter = new MyPresenter(this);
                presenter.init();
            } else {
                presenter.init();
            }
        }
    }

    boolean isfirst = true;

    @Override
    public void onResume() {
        if (isfirst) {

        } else {
            presenter.init();
        }
        super.onResume();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my;
    }


    @OnClick({R.id.avatar, R.id.gocertification, R.id.none, R.id.earnings, R.id.cashwithdrawal})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.avatar:
                isfirst = false;
                if (!TokenManager.INSTANCE.online()) {
                    LoginActivity.start(getActivity());
                } else {
                    if (UserInfoManger.INSTANCE.noRealName()) {
                        gorealname();
                        return;
                    } else {
                        PersonalInformationActivity.start(getActivity());
                    }
                }
                break;
            case R.id.gocertification:
                isfirst = false;
                if (!TokenManager.INSTANCE.online()) {
                    LoginActivity.start(getActivity());
                } else {
                    IDCardAuthActivity.start(getActivity());
                    break;
                }
            case R.id.none:
                isfirst = false;
                LoginActivity.start(getActivity());
                break;
          /*  case R.id.performance:
=======
            case R.id.performance:
                isfirst = false;
>>>>>>> bc652088d192eff45f645f71252b47669309766e
                WebActivity.startToH5(getActivity(), "partnerPerformance");
                break;*/
            case R.id.earnings:
                isfirst = false;
                String monthbalance = monthIncome.getText().toString();
                String perplebalance = balance.getText().toString();
                WebActivity.startToH5(getActivity(), "myAccount");
                break;
            case R.id.cashwithdrawal:
                isfirst = false;
                ReceivablesActivity.start(getActivity(), UserInfoManger.INSTANCE.getUser().getBalance() + "");
                break;
        /*    case R.id.next01:
                guider03.setVisibility(View.GONE);
                guider04.setVisibility(View.VISIBLE);
                guider05.setVisibility(View.GONE);
                break;
            case R.id.next02:
                guider03.setVisibility(View.GONE);
                guider04.setVisibility(View.GONE);
                guider05.setVisibility(View.VISIBLE);
                break;
            case R.id.know:
                none.setVisibility(View.GONE);
                visible.setVisibility(View.VISIBLE);
                funcs.setVisibility(View.VISIBLE);
                guider03.setVisibility(View.GONE);
                guider04.setVisibility(View.GONE);
                guider05.setVisibility(View.GONE);


                break;*/
        }
    }

    public void gorealname() {
        final RealNamePopView popView = new RealNamePopView(getActivity());
        popView.setOnClickListener(new RealNamePopView.OnClickListener() {
            @Override
            public void onClickConfirm(View v) {
                IDCardAuthActivity.start(getActivity());
                popView.dismiss();
            }
        });
        popView.show();
    }

    static int REQUEST_CODE_ASK_CALL_PHONE = 0;

    @Override
    public void onClickItem(MyModel.ICON icon) {
        isfirst = false;
        //支付设备
        if (icon == MyModel.ICON.PAY_DEVICE) {
            if (!TokenManager.INSTANCE.online()) {
                LoginActivity.start(getActivity());
            } else {
                if (UserInfoManger.INSTANCE.getUser().getRealNameAuthStatus() == 0) {
                    gorealname();
                } else {
                    if (UserInfoManger.INSTANCE.getUser().getActiviteStatus() == 0) {
                        HeadIdCardActivity.start(getActivity());
                    }
                    if (UserInfoManger.INSTANCE.getUser().getActiviteStatus() == 1) {
                        EquipmentCardSlotActivity.start(getActivity());
                    }
                }
            }
        }
        if (icon == MyModel.ICON.TEAM) {
            if (!TokenManager.INSTANCE.online()) {
                LoginActivity.start(getActivity());
            } else {
                UserInfo userInfo = UserInfoManger.INSTANCE.getUser();
                String inviterPhone = UserInfoManger.INSTANCE.getUser().getInvitePhone();
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + inviterPhone);
                intent.setData(data);
                startActivity(intent);
            }
        }
        if (icon == MyModel.ICON.CONTACT) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + "400-843-3388");
            intent.setData(data);
            startActivity(intent);
        }
        if (icon == MyModel.ICON.SETTING) {
            SettingActivity.start(getActivity());
        }
        if (icon == MyModel.ICON.BANK_CARD) {
            if (!TokenManager.INSTANCE.online()) {
                LoginActivity.start(getActivity());
            } else {
                if (UserInfoManger.INSTANCE.getUser().getRealNameAuthStatus() == 0) {
                    gorealname();
                } else {
                    CardActivity.start(getActivity());
                }
            }
        }
        if (icon == MyModel.ICON.DEVICE_ORDER) {
            if (!TokenManager.INSTANCE.online()) {
                LoginActivity.start(getActivity());
            } else {
                if (UserInfoManger.INSTANCE.getUser().getRealNameAuthStatus() == 0) {
                    gorealname();
                } else {
                    OrderListActivity.start(getActivity());
                }
            }
        }
        if (icon == MyModel.ICON.DEVIECEMANAGEMENT) {
            if (!TokenManager.INSTANCE.online()) {
                LoginActivity.start(getActivity());
            } else {
                if (UserInfoManger.INSTANCE.getUser().getRealNameAuthStatus() == 0) {
                    gorealname();
                } else {
                    if (UserInfoManger.INSTANCE.getUser().getUserType() == 5 || UserInfoManger.INSTANCE.getUser().getUserType() == 4) {
                        PartnerEquipmentActivity.start(getActivity());
                    } else {
                        goShop();
                    }
                }
            }
        }
        if (icon == MyModel.ICON.RECOMMEND) {
            if (!TokenManager.INSTANCE.online()) {
                LoginActivity.start(getActivity());
            } else {
                if (UserInfoManger.INSTANCE.getUser().getRealNameAuthStatus() == 0) {
                    gorealname();
                } else {
                    WebActivity.startToH5(getActivity(),"RewardDescription");
                   /* if (UserInfoManger.INSTANCE.getUser().getUserType() == 5 || UserInfoManger.INSTANCE.getUser().getUserType() == 4) {
//                        String path = "RewardDescription";
//                        WebActivity.startToH5(getActivity(), "", path);
                        String path = String.format("invite?userPhone=%s&username=%s", UserInfoManger.INSTANCE.getUser().getUseraccount(), UserInfoManger.INSTANCE.getUser().getUsername());
                        WebActivity.startToH5(getActivity(),"RewardDescription");
                    } else {
                        goShop();
                    }*/
                }
            }
        }
        if (icon == MyModel.ICON.POWER) {
            if (!TokenManager.INSTANCE.online()) {
                LoginActivity.start(getActivity());
            } else {
                if (UserInfoManger.INSTANCE.getUser().getRealNameAuthStatus() == 0) {
                    gorealname();
                } else {
                    if (UserInfoManger.INSTANCE.getUser().getUserType() == 5 || UserInfoManger.INSTANCE.getUser().getUserType() == 4) {
                        presenter.getwarrant();
                    } else {
                        goShop();
                    }
                }
            }
        }

/*
        if (icon == MyModel.ICON.SUGGEST) {
            PlanParticularsActivity.start(getActivity(),"123465");
        }
*/
    }

    public void goShop() {
        final GoShopPopView popView = new GoShopPopView(getActivity());
        popView.setOnClickListener(new GoShopPopView.OnClickListener() {
            @Override
            public void onClickConfirm(View v) {
                popView.dismiss();
                if (MyFragment.this.goShopListener == null) {
                    return;
                }
                MyFragment.this.goShopListener.goShop();
            }
        });
        popView.show();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 0:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    /*String phoneNum = merchantuserlistTxt[6];
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phoneNum);
                    intent.setData(data);
                    startActivity(intent);*/
                } else {
                   /* String phoneNum = merchantuserlistTxt[6];
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phoneNum);
                    intent.setData(data);
                    startActivity(intent);*/
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void showMyFuncItems(List<MyModel.IconItem> iconItems) {
        funcs.setOverScrollMode(View.OVER_SCROLL_NEVER);
        funcs.setLayoutManager(new GridLayoutManager(getContext(), 3));
        funcs.setAdapter(new IconAdapter(iconItems, this));
    }

    @Override
    public void showUserInfo(UserInfo userInfo) {
        /*if (UserInfoManger.INSTANCE.getUser().getAvatar()==null||UserInfoManger.INSTANCE.getUser().getAvatar().equals("")){
            avatar.setDrawable(getResources().getDrawable(R.mipmap.tx));
        }else {
            Glide.with(this).load(userInfo.getAvatar()).into(avatar);
        }*/
        if (UserInfoManger.INSTANCE.getUser().getUsername() == null || UserInfoManger.INSTANCE.getUser().getUsername().equals("")) {
            username.setText(UserInfoManger.INSTANCE.getUser().getUseraccount());
        } else {
            username.setText(UserInfoManger.INSTANCE.getUser().getUsername());
        }
    }

    @Override
    public void showPartner() {
        partnericon.setImageResource(R.mipmap.hehuoren_n);
        //performance.setVisibility(View.VISIBLE);
        earnings.setVisibility(View.VISIBLE);
        cashwithdrawal.setVisibility(View.VISIBLE);
        presenter.monthProfit();
    }

    @Override
    public void showvipPartner() {
        vipicon.setImageResource(R.mipmap.vip_n);
        earnings.setVisibility(View.VISIBLE);
        cashwithdrawal.setVisibility(View.VISIBLE);
        presenter.monthProfit();
    }

    @Override
    public void enshowPartner() {
        partnericon.setImageResource(R.mipmap.hehuoren_l);
        // performance.setVisibility(View.GONE);
        earnings.setVisibility(View.GONE);
        cashwithdrawal.setVisibility(View.GONE);
    }

    @Override
    public void showVip() {
        vipicon.setImageResource(R.mipmap.vip_n);
        earnings.setVisibility(View.VISIBLE);
        cashwithdrawal.setVisibility(View.VISIBLE);
        presenter.monthProfit();
    }

    @Override
    public void enshowVip() {
        vipicon.setImageResource(R.mipmap.vip_l);
    }

    @Override
    public void showBalance(String s) {
        balance.setText(s);
    }

    @Override
    public void showCertification() {
        gocertification.setVisibility(View.VISIBLE);
    }

    @Override
    public void enshowCertification() {
        gocertification.setVisibility(View.GONE);
    }

    @Override
    public void showMonthProfit(String monthProfit) {
        monthIncome.setText(String.format("本月收益 +%.2f", Double.parseDouble(monthProfit)));
    }

    @Override
    protected void start() {

    }

    @Override
    public void showLogin() {
        none.setVisibility(View.VISIBLE);
        visible.setVisibility(View.GONE);
    }

    @Override
    public void showMy() {
        none.setVisibility(View.GONE);
        visible.setVisibility(View.VISIBLE);
       /* if (SharedPreferencesUtil.getMyShow()) {
            none.setVisibility(View.GONE);
            visible.setVisibility(View.VISIBLE);
            funcs.setVisibility(View.VISIBLE);
            guider03.setVisibility(View.GONE);
            guider04.setVisibility(View.GONE);
            guider05.setVisibility(View.GONE);
        } else {
            none.setVisibility(View.GONE);
            visible.setVisibility(View.GONE);
            funcs.setVisibility(View.GONE);
            guider03.setVisibility(View.VISIBLE);
            guider04.setVisibility(View.GONE);
            guider05.setVisibility(View.GONE);
        }*/
    }
    public interface showMyInterface{
        void showMyPage();
    }
    public void showMyPage(){

    }


    @Override
    public void showPower(MyModel.WarrantBean warrantBean) {
        String date = warrantBean.getPartnerLicenseData();
        String str = date.substring(0, date.indexOf(" "));
        String[] st = str.split("-");
        if (st.length > 2) {
            String stDate = String.format("%s年%s月%s日", st[0], st[1], st[2]);
            String path = String.format("authorization?username=%s&inviteCode=%s&date=%s", warrantBean.getUsername(), warrantBean.getUseraccount(), stDate);
            WebActivity.startToH5(getActivity(), "授权书", path);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        monthIncome = rootView.findViewById(R.id.monthIncome);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }



    public interface GoShopListener {
        void goShop();
    }

    private GoShopListener goShopListener;

    public void setGoShopListener(GoShopListener goShopListener) {
        this.goShopListener = goShopListener;
    }
}